package com.sms.demo.utils;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Tom
 * @Date: 2022/03/11/17:30
 * @Description:
 */

/**
 *@ClassName sendSmsUtil
 *@Description
 *@Author 王琛
 *@Date 2022/3/11 17:30
 @Version 1.0
 */
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.sms.demo.entity.TencentSmsConstant;
import org.json.JSONException;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Random;
/**
 * @Description: 发送短信的工具类
 * @Author: ws
 * @date: 2019/10/12
 */
@Component
public class SendSmsUtil {
    @Resource
    RedisUtil redisUtil;
    /**
     * @Description: 发送短信
     * @Param: [photoNumber]
     * @return java.lang.String
     * @Author: ws
     * @date: 2019/10/12
     */
    public String sendSms(String phone){
        // 生成随机数
        String code=createRodom();
        SmsSingleSenderResult result =null;
        try {
            // 模板需要的参数
            String[] params = {code};
            SmsSingleSender ssender = new SmsSingleSender(TencentSmsConstant.APP_ID,TencentSmsConstant.APP_KEY);
            // 单发短信
            result = ssender.sendWithParam("86", phone, TencentSmsConstant.TEMPLATE_ID, params, null, "", "");
        } catch (JSONException e) {
            // json解析错误
            e.printStackTrace();
        } catch (IOException e) {
            // 网络IO错误
            e.printStackTrace();
        } catch (HTTPException e) {
            e.printStackTrace();
        }
        // 保存验证码到redis
        redisUtil.set(phone,code, TencentSmsConstant.EFFECTIVE_Time);
        if(!"OK".equals(result.errMsg)){
            return "验证码发送失败";
        }
        return result.errMsg;
    }
    /**
     * @Description: 创建6位数随机数
     * @return java.lang.String
     * @Author: ws
     * @date: 2019/10/12
     */
    public String createRodom(){
        Random random = new Random();
        String result="";
        for (int i=0;i<6;i++)
        {
            result+=random.nextInt(10);
        }
        return result;
    }
}